$(function(){
	$('#header-srch-btn').click(function(e){
	});

//	$('#header-srch').keyup(function(e){
//	});

	var sock;
	var tokenLast;

	function send(message){
		if(sock.readyState === SockJS.OPEN){
			console.log('sending message')
			sock.send(JSON.stringify(message));
		}else{
			console.log('The socket is not open.');
		}
	}

	$('#login-link').click(function(e){
		var token = '' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000);
		$(this).attr('href', '/wx/auth/login/qr?token=' + token);
		console.log(token);
		tokenLast = token;

		if(!sock){
			sock = new SockJS('/ws/socketio/');
			sock.onopen = function(){
				console.log('open');
				send({action: 'wx-auth-login-mapping-token', token: tokenLast});
			};

			sock.onmessage = function(e){
				console.log(e.data);

				if(!e.data)
					return;

				var obj = JSON.parse(e.data);
				if(obj && 'reject' == obj.action){
					alert('用户拒绝登陆。。。');
					return;
				}

				if(obj && 'loginok' == obj.action){
					$.get('/wx/auth/login/ok?isAjax=1&token=' + tokenLast, function(data){
						if(data.nickname){
							// <span id="header-msg-count"></span> 
							$('#login-user-nickname').html(data.nickname + '<i class="ml5 caret caret-down caret-b-fff"></i>');
							$('#login-user-headimgurl').attr('src', data.headimgurl);
							$('.logout-field').hide();
							$('.login-field').show();

							$('#lightbox').find('.lb-loader').trigger('click');
						}
					});
					return;
				}
			};
		}else{
			send({action: 'wx-auth-login-mapping-token', token: tokenLast});
		}
	});

	$('#logout-link').click(function(e){
		$.get('/wx/auth/logout');

		$('#login-user-nickname').html('');
		$('.login-field').hide();
		$('.logout-field').show();
	});

	window.onbeforeunload = function(){
		if(sock)
			sock.close();
	};

});